//https://leetcode.cn/problems/reverse-words-in-a-string-iii/solutions/393471/fan-zhuan-zi-fu-chuan-zhong-de-dan-ci-iii-by-lee-2/

void swap(char& x, char& y)
{
    char temp = x;
    x = y;
    y = temp;
}

class Solution {
public:
    string reverseWords(string s) {
        int begin = 0;
        int pos = s.find(' ', begin);
        int end = pos - 1;

        //只有一个单词不包含空格
        if (pos == string::npos)
        {
            end = s.size() - 1;
            while (begin <= end)
            {
                swap(s[begin], s[end]);
                begin++;
                end--;
            }
            return s;
        }

        while (end < s.size())
        {
            while (begin <= end)
            {
                swap(s[begin], s[end]);
                begin++;
                end--;
            }

            begin = pos + 1;
            pos = s.find(' ', begin);
            end = pos - 1;

            //最后一个单词的翻转
            if (pos == string::npos)
            {
                end = s.size() - 1;
                while (begin <= end)
                {
                    swap(s[begin], s[end]);
                    begin++;
                    end--;
                }
                break;

            }

        }

        return s;

    }
};